package com.yueya.im.node.handler.impl;

import com.yueya.auth.config.AuthProperties;
import com.yueya.auth.model.AuthUserDto;
import com.yueya.auth.utils.JwtUtil;
import com.yueya.im.common.api.ImContext;
import com.yueya.im.common.util.JsonMapper;
import com.yueya.im.node.messages.LoginMsg;
import com.yueya.im.node.messages.MsgType;
import com.yueya.im.node.util.CacheUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class LoginHandler extends DefaultHandler {

    @Autowired
    private AuthProperties properties;
    @Override
    public void onMessage(ImContext ctx, int msgType, byte[] message, long msgId) {
        if(ctx.getSessionId() != null) {
            return;
        }
        AuthUserDto authUserDto = null;
        try {
            String msg  = new String(message,"utf-8");
            LoginMsg loginDto = JsonMapper.getInstance().fromJson(msg, LoginMsg.class);
            Jws<Claims> parseJwtPayload =  JwtUtil.parseJwtPayload(loginDto.token,properties.getPublicKey(),properties.getSignMode());
            authUserDto = JwtUtil.getClaims(parseJwtPayload.getBody());
            String device = loginDto.device;
            CacheUtil.addItem(authUserDto.getUserId());
            ctx.connect(authUserDto.getUserId(),device);
            ctx.sendToClient(MsgType.LOGIN_RESP.getNumber(),JsonMapper.toJsonString(authUserDto));
        } catch (UnsupportedEncodingException e) {
            logger.error("编码异常:",e);
        }
    }

    public static List<Map<String,Object>> list(){
        AuthUserDto authUserDto1=new AuthUserDto();
        authUserDto1.setUserId("001");
        authUserDto1.setName("用户1");
        AuthUserDto authUserDto2=new AuthUserDto();
        authUserDto2.setUserId("002");
        authUserDto2.setName("用户2");
        AuthUserDto authUserDto3=new AuthUserDto();
        authUserDto3.setUserId("003");
        authUserDto3.setName("用户3");
        AuthUserDto authUserDto4=new AuthUserDto();
        authUserDto4.setUserId("004");
        authUserDto4.setName("用户4");
        List<AuthUserDto> list = new ArrayList<>();
        list.add(authUserDto1);
        list.add(authUserDto2);
        list.add(authUserDto3);
        list.add(authUserDto4);
        return list.stream().map(r->{
            Map<String,Object> map = new HashMap<>();
            map.put("key",1);
            map.put("user",r);
            return map;
        }).collect(Collectors.toList());
    }
}

